<?php
include_once 'application/controllers/AbstractController.php';
include_once 'application/models/Utilisateur.php';
include_once 'application/models/Menu.php';
include_once 'application/models/Batterie.php';

class DownloadController extends AbstractController 
{
	private static $_VISIBILITY_PUBLIC_READ = 0;
	private static $_VISIBILITY_PUBLIC_WRITE = 1;
	private static $_VISIBILITY_PRIVATE = 2;
	
	function indexAction()
    {
		parent::indexAction();
    	HttpUtil::do405();
    }
		
	function pictolemmesHtmlAction()
    {
		parent::indexAction();
		$workDir = Zend_Registry::getInstance()->get('config')->directory->work;
		$s = Zend_Registry::getInstance()->get('config')->directory->fileseparator;
		
		// __userdata__ : get user params
		if (isset($this->user)) {
			$userData = Utilisateur::publicUserDatas($this->user);
		}else{
    		HttpUtil::do405();
			return;
		}
		$__userdata__ = json_encode($userData);


		
		
		// __listOfAreas__
		// get menu
		$id = $userData['menu_id'];
		if ($id == 'private') {
			// get my own menu
			if ($this->user->private_menu_id <= 0) {
				HttpUtil::do404();
			}

			$table = new Menu();
			$where = $table->getAdapter()->quoteInto('id = ?', $this->user->private_menu_id);
		    $menuRows = $table->fetchAll($where);
		    
	    	$menu = $table->getObjectFromRow($menuRows[0]);
		    
		    if (!isset($menu) || !isset($menu['menu'])) {
				HttpUtil::do404();
		    }
		    
		    $__listOfAreas__ = json_encode($menu['menu']);
		}else{
			// get menu from id
		    $table = new Menu();
			$whereId = $table->getAdapter()->quoteInto('id = ?', $id);
			$whereViz = $table->getAdapter()->quoteInto('visibility = ?', self::$_VISIBILITY_PUBLIC_READ);
			$wherePrivate = $table->getAdapter()->quoteInto('id = ?', $this->user->private_menu_id);
			$menuRows = $table->fetchAll(array($whereId, $whereViz.' OR '.$wherePrivate));
		    
	    	$menu = $table->getObjectFromRow($menuRows[0]);
	    	
		    if (!isset($menu) || !isset($menu['menu'])) {
				HttpUtil::do404();
		    }
		    
		    $__listOfAreas__ = json_encode($menu['menu']);
		}

	    
		// __batteries__
		$__batteries__ = array();
		foreach($menu['menu'] as $menuContent) {
	    	if (isset ($menuContent['sousmenu'])) {
				foreach($menuContent['sousmenu'] as $sousmenuContent) {
		    		if (isset ($sousmenuContent['params'])) {
						$query = parse_url('http://peut-importe.com?'.$sousmenuContent['params'], PHP_URL_QUERY);
						parse_str($query, $params);
		    			$tid = isset($params['tid'])?$params['tid']:null;
		    			$ids = isset($params['ids'])?$params['ids']:null;
		    			$bats = Batterie::listBatteries($tid, $ids, false, $this->user);
		    			if ($bats !== false) {
							// Base64
							foreach($bats['batteries'] as $keybat => $bat) {
								foreach($bat['exercices']['series'] as $keyserie => $serie) {
									foreach($serie['page'] as $keypage => $page) {
										foreach($page['question'] as $keyquestion => $question) {
											// images
											if (isset($question['image_name']) && $question['image_name'] != "") {
												$fileToEncode = 
													$workDir.
													$s.'batteries'.
													$s.$bat['id'].
													$s.$question['id'].
													$s.$question['image_name'];
												$bats['batteries'][$keybat]['exercices']['series'][$keyserie]['page'][$keypage]['question'][$keyquestion]['image_name'] = $this->encodeBase64($fileToEncode);
											}
											// audio
											if (isset($question['sound_name']) && $question['sound_name'] != "") {
												$fileToEncode = 
													$workDir.
													$s.'batteries'.
													$s.$bat['id'].
													$s.$question['id'].
													$s.$question['sound_name'];
												$bats['batteries'][$keybat]['exercices']['series'][$keyserie]['page'][$keypage]['question'][$keyquestion]['sound_name'] = $this->encodeBase64($fileToEncode);
											}
										}
									}
								}
							}
							$__batteries__[$sousmenuContent['params']] = $bats['batteries'];
		    			}
		    		}
				}
	    	}
		}
		$__batteries__ = json_encode($__batteries__, JSON_FORCE_OBJECT);
		
		
		// download infos
		$date = new DateTime();
		$__downloadInfo__ = 'Enregistré le '.$date->format('d/m/Y').' à '.$date->format('H:i').' par '.$this->user->firstname.' '.$this->user->lastname;
		
		
		// get file
		$dir = Zend_Registry::getInstance()->get('config')->directory->download;
		$filePath = $dir.'menu.html';
		
		$fp = fopen($filePath,'rb', 0);
	    if (!$fp) {
				HttpUtil::do405();
	    }
	    $file = fread($fp,filesize($filePath));
	    fclose($fp);
	    
	    // file
	    $file = str_replace('__userdata__', $__userdata__	, $file);
	    $file = str_replace('__listOfAreas__', $__listOfAreas__, $file);
	    $file = str_replace('__batteries__', $__batteries__, $file);
	    $file = str_replace('__downloadInfo__', $__downloadInfo__, $file);

	    header('Content-Type: text/html; charset=utf-8'); 
		$this->view->data = $file;




/*	    
		
//	    header('Content-Type: text/html; charset=utf-8'); 

//header("Content-disposition: attachment; filename=pictolemmes.html"); 
//header("Content-Type: application/force-download"); 
//header("Content-Transfer-Encoding: text/html\n");
////header("Content-Length: ".filesize($chemin . $Fichier_a_telecharger)); 
//header("Pragma: no-cache"); 
//header("Cache-Control: must-revalidate, post-check=0, pre-check=0, public"); 
//header("Expires: 0"); 
//		$this->view->data = $file;

		//create zip
			    
		$zip = new ZipArchive();
		$time = time();
		$filename = $workDir.$s."pictolemmes".$time.".zip";
		
		if ($zip->open($filename, ZipArchive::CREATE)!==TRUE) {
		    exit("Impossible d'ouvrir le fichier <$filename>\n");
		}
		
		$zip->addFromString("pictolemmes.html", $file);
		$zip->close();
		
		$fp = fopen($filename,'rb', 0);
	    if (!$fp) {
				HttpUtil::do405();
	    }
	    $contentSize = filesize($filename);
	    $contents = fread($fp,$contentSize);
	    fclose($fp);

		header("Content-disposition: attachment; filename=pictolemmes.zip");
		header("Content-type: application/zip");
		header("Content-Length: ".$contentSize); 
		
	    $this->view->data = $contents;
*/
    }
    
    
    function getAction()
    {
		parent::getAction();
    	HttpUtil::do405();
    }
    
    function postAction()
    {
		parent::postAction();
    	HttpUtil::do405();
    }
    
    function putAction()
    {
		parent::putAction();
    	HttpUtil::do405();
    }
    
    function deleteAction()
    {
		parent::deleteAction();
    	HttpUtil::do405();
    }
    
    private function encodeBase64($fileToEncode)
    {
	    $fp = fopen($fileToEncode,'rb', 0);
	    if (!$fp) return '';
	    $file = fread($fp,filesize($fileToEncode));
	    fclose($fp);
	    $encoded = base64_encode($file);
		$finfo = finfo_open(FILEINFO_MIME_TYPE); 
	    return 'data:'.finfo_file($finfo, $fileToEncode).';base64,'.$encoded;
    }
}
